import {debounce, DebouncedFunc, DebounceSettings} from 'lodash-es';
import {useEffect, useRef} from 'react';
import {Func} from '@/types/utils';

const useDebounce = (wait?: number, options?: DebounceSettings) => {
    const myRef = useRef<DebouncedFunc<Func>>();

    if (!myRef.current) {
        // 将debounce创建的节流函数返回，通过调用节流函数，并通过参数传递action
        myRef.current = debounce((func: Func) => {
            func();
        }, wait, options);
    }

    useEffect(() => {
        return () => {
            delete myRef.current;
            console.log('删除');
        };
    }, []);

    return myRef.current;
};

export default useDebounce;
